<?php
/**
 *author:韩帅
 *createtime:2017/6/19 16:53
 *description:
 */
namespace App\Http\Controllers\App;

use App\Models\ShopUser;
use App\Models\ShopUserCenter;
use App\Models\User;
use App\Models\UserServerBalance;
use App\Models\UserShopBalance;
use Illuminate\Http\Request;
use App\Models\ShopUserBalanceLog;
use App\Http\Controllers\App\BaseController;
use Illuminate\Support\Facades\DB;

class ShopUserController extends BaseController
{
    /**
     * 店铺会员列表
     */
    public function userList(Request $request)
    {
        $return   = [];//存储获取数据

        $shopId   = $this->shop_id;

        if (empty($shopId)) {
            return self::error('请先登录');
        }

        $name   = trim($request->input('name',''));
        $tel    = trim($request->input('tel',''));

        $obj = ShopUser::where('shop_id',$shopId);

        //判断是否有筛选条件
        if (!empty($name)) {

            $obj->where('real_name','like','%'.$name.'%');
        }
        if (!empty($tel)) {

            $obj->where('user_mobile',$tel);
        }

        $data   = $obj->paginate($this->pageSize)->toArray();

        $return = $data;

        if (empty($return['data'])) {
            return self::json($return,'数据为空',200);
        }
        return self::json($return,'成功',200);
    }

    /**
     * 会员详情
     */
    public function userInfo(Request $request)
    {

        $return = [];
        $userId = $request->get('user_id','');

        if (empty($userId)) {
            return self::json(array(),'ID不能为空',400);
        }

        $data   = ShopUser::find($userId);

        $return = $data;

        if (empty($data)) {

            return self::json($return,'数据为空',200);
        }
        return self::json($return,'成功',200);
    }

    /**
     * 会员修改
     */
    public function userUpdate(Request $request)
    {

        $userId        = trim($request->input('userId',''));
        $user_nickname = trim($request->input('user_nickname',''));  //昵称
        $into_queque   = $request->input('into_queque','');          //是否能进队列
        $real_name     = trim($request->input('real_name',''));      //真实姓名
        $id_card       = trim($request->input('id_card',''));         //身份证号

       if (empty($userId) || empty($user_nickname) || empty($into_queque) || empty($real_name) || empty($id_card)) {
           return self::error('必填字段不能为空');
       }

       $obj = ShopUser::find($userId);

       if (empty($obj)) {

           return self::error('本条记录不存在');
        }

        $obj->user_nickname = $user_nickname;
        $obj->into_queque   = $into_queque;
        $obj->real_name     = $real_name;
        $obj->id_card       = $id_card;

        $res = $obj->save();

        if ($res == false) {
            return self::error(array(),'更新失败',400);
        }
        return self::success('成功');
    }

    /**
     * 商铺会员充值
     */
    public function shopPay(Request $request)
    {
        $user_id = $request->input('user_id','');
        $shop_id = $this->shop_id;
        $money   = intval($request->input('money'));

        if (empty($user_id) || empty($shop_id) || empty($money)) {

            return self::error('必填字段不能为空');
        }

        $objA = ShopUserCenter::where('user_id',$user_id)->where('shop_id',$shop_id)->first();   //用户资金表

        if (empty($objA)) {

            return self::error('店铺会员信息不完善');
        }

        $objB = new UserShopBalance();  //用户资金流水表

        //开事务
        $res = false;
        DB::beginTransaction();
        try{

           $objA->balance = $objA->balance+$money;
           $objA->save();

           $objB->user_id     =     $user_id;                       //用户ID
           $objB->shop_id     =     $shop_id;                       //店铺ID
           $objB->order_sn    =     '';                             //订单号
           $objB->money       =     $money;                         //金额
           $objB->type        =     ShopUserCenter::TYPE_GET_PAY;   //类型为充值
           $objB->action_type =     ShopUserCenter::ACTION_TYPE_IN; //收入
           $objB->status      =     2;                              // 已审核
           $objB->note        =     "商户后台充值".$money."元";     // 日志记录
           $objB->admin_id    =     $shop_id;                       //操作人是店铺ID

           $objB->save();
            // 提交事务
            DB::commit();
            $res = true;
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
        }

        if ($res == true) {
            return self::success('成功');
        }
        return self::json($e,'失败',400);
    }

    /**
     * 商铺会员扣钱
     */
    public function shopPayNo(Request $request)
    {
        $user_id = $request->input('user_id','');
        $shop_id = $this->shop_id;
        $money   = intval($request->input('money'));

        if (empty($user_id) || empty($shop_id) || empty($money)) {

            return self::error('必填字段不能为空');
        }

        $objA = ShopUserCenter::where('user_id',$user_id)->where('shop_id',$shop_id)->first();   //用户资金表

        if (empty($objA)) {
            return self::error('店铺会员信息不完善');
        }

        //1这里比充值多一步,判断余额是否够扣
        if ($objA->balance < $money) {
            return self::error('会员余额不足');
        }

        $objB = new UserShopBalance();  //用户资金流水表

        //开事务
        $res = false;
        DB::beginTransaction();
        try{

            //2.这里再次判断余额是否够扣
            if ($objA->balance-$money < 0) {
                return self::error('会员余额不足');
            }

            $objA->balance = $objA->balance-$money;
            $objA->save();

            $objB->user_id     =     $user_id;                       //用户ID
            $objB->shop_id     =     $shop_id;                       //店铺ID
            $objB->order_sn    =     '';                             //订单号
            $objB->money       =     $money;                         //金额
            $objB->type        =     ShopUserCenter::TYPE_PAY;   //类型为扣款
            $objB->action_type =     ShopUserCenter::ACTION_TYPE_GO; //支出
            $objB->admin_id    =     $shop_id;                       //操作人是店铺ID

            $objB->save();
            // 提交事务
            DB::commit();
            $res = true;
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
        }

        if ($res == true) {
            return self::success('成功');
        }
        return self::json($e,'失败',400);
    }

    /**
     * 店铺会员充值前余额查看
     */
    public function userBalance(Request $request)
    {
        $return  = [];
        $user_id = $request->input('user_id','');
        $shop_id = $this->shop_id;

        if (empty($user_id)) {

            return self::error('会员ID不能为空');
        }

        $data  = ShopUserCenter::where('user_id',$user_id)->where('shop_id',$shop_id)
                                                          ->first();

        $return = $data;

        if (empty($return)) {
            return self::json($return,'获取数据为空');
        }
        return self::json($return,'成功');
    }

    /**
     * 协助绑定
     */

    public function searchUser(Request $request)
    {
        $return      = [];
        $user_mobile = $request->input('user_mobile','');

        if (empty($user_mobile)) {

            return self::error('手机号不能为空');
        }

        $data = User::where('status',1)->where('user_mobile',$user_mobile)->where('shop_id',0)
                                        ->select('id','user_name','user_mobile','user_sex','user_age','id_card','real_name')
                                        ->first();

        if (empty($data)) {

            return self::json($data,'获取数据为空',400);
        }

        return self::json($data,'成功',200);
    }

    /**
     * bindToShop协助绑定
     */
    public function bindToShop(Request $request)
    {
        $id = $request->input('id','');

        if (empty($id)) {

            return self::error('ID不能为空');
        }

        $obj  = User::find($id);
        $objB = new ShopUserCenter();
        if (empty($obj)) {

            return self::error('ID异常');
        }

        if (!empty($obj['shop_id'])) {

            return self::error('该用户已经绑定过店铺');
        }

        $obj->shop_id = $this->shop_id;

        $data = $objB->where('user_id',$id)->first();

        if (empty($data)) {

            $objB->user_id = $id;
            $objB->balance = 0;
            $objB->shop_id = $this->shop_id;
            $objB->status  = 1;

            $objB->save();
        }


        $res = $obj->save();

        if ($res == false) {
            return self::error('绑定失败');
        }

        return self::success('绑定成功');
    }

    /**
     * 交易流水(商户端)
     */
    public function shopBalanceLog(Request $request)
    {
        $return      = [];                       //存放查询出的数据
        $newArr      = [];                       //存放新数组
        $id          = $request->input('user_id','');       //用户ID;
        $type        = $request->input('type',0);
        $s_time      = $request->input('s_time',0);
        $e_time      = $request->input('e_time',0);

        $obj         = new ShopUserBalanceLog();

        if (empty($id)) {

            return self::error('会员ID不能为空');
        }
        if (!empty($type)) {

            $obj = $obj->where('type',$type-1);
        }
        if($s_time > 0){

            $obj = $obj->where('created_at','>=',$s_time);
        }

        if($e_time > 0){

            $obj = $obj->where('created_at','<=',$e_time);
        }

        $data = $obj->where('user_id',$id)->orderBy('created_at','desc')->paginate(10)->toArray();

        $return = $data;

        if (empty($return['data'])) {

            $newArr['total']        = $return['total'];
            $newArr['per_page']     = $return['per_page'];
            $newArr['current_page'] = $return['current_page'];
            $newArr['last_page']    = $return['last_page'];
            $newArr['balance_log']  = [];

            return self::json($newArr,'数据为空',200);
        }

        $objB    = new UserServerBalance();  //在UserServerBalance模型里面转化数据
        $newArr  = $objB->translate($return);

        return self::json($newArr,'成功',200);
    }

    /**
     * 配合文斌,传用户ID,查出用户的订单记录
     */
    public function ShopUserLog(Request $request)
    {
        $return      = [];                       //存放查询出的数据
        $newArr      = [];                       //存放新数组
        // $id          = $request->input('user_id','');       //用户ID;
        $type        = $request->input('type',0);
        $s_time      = $request->input('s_time',0);
        $e_time      = $request->input('e_time',0);

        $shop_id     = $this->shop_id; 

        $obj         = new ShopUserBalanceLog();

        if (empty($shop_id)) {

            return self::error('未登录');
        }
        if (!empty($type)) {

            $obj = $obj->where('type',$type-1);
        }
        if($s_time > 0){

            $obj = $obj->where('created_at','>=',$s_time);
        }

        if($e_time > 0){

            $obj = $obj->where('created_at','<=',$e_time);
        }

        $data = $obj->where('shop_id',$shop_id)->orderBy('created_at','desc')->paginate(10)->toArray();

        $return = $data;

        if (empty($return['data'])) {

            $newArr['total']        = $return['total'];
            $newArr['per_page']     = $return['per_page'];
            $newArr['current_page'] = $return['current_page'];
            $newArr['last_page']    = $return['last_page'];
            $newArr['balance_log']  = [];

            return self::json($newArr,'数据为空',200);
        }


        return self::json($return,'成功',200);
    }
}